<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="72px">
      <!-- <el-form-item label="商品规格ID" prop="skuId">
        <el-input
          v-model="queryParams.skuId"
          placeholder="请输入商品规格ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="商品编号" prop="goodsId">
        <el-input v-model="queryParams.goodsId" placeholder="请输入商品编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="订单ID" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单ID" prop="workId">
        <el-input
          v-model="queryParams.workId"
          placeholder="请输入工单ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="变动类型" prop="changeType">
        <el-select v-model="queryParams.changeType" placeholder="请选择变动类型" clearable>
          <el-option v-for="dict in change_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="业务参考号" prop="businessRef">
        <el-input
          v-model="queryParams.businessRef"
          placeholder="请输入业务参考号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in wdm_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['ruoyi:stockLogs:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['ruoyi:stockLogs:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['ruoyi:stockLogs:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['ruoyi:stockLogs:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表单 -->
    <el-table v-loading="loading" :data="stockLogsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60px" align="center" prop="logId" />
      <el-table-column label="商品名称" align="center" prop="goodsName">
        <template #default="scope">
          <el-button type="text">
            <el-link type="primary" @click="handleGoodsInfo(scope.row)">{{
              scope.row.goodsName
            }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <!-- <el-table-column label="商品规格ID" align="center" prop="skuId" /> -->
      <!-- <el-table-column label="订单ID" align="center" prop="orderId" /> -->
      <!-- <el-table-column label="工单ID" align="center" prop="workId" /> -->
      <el-table-column label="变动数量" align="center" prop="changeQuantity" />
      <!-- <el-table-column label="变动类型" align="center" prop="changeType">
        <template #default="scope">
          <dict-tag :options="change_type" :value="scope.row.changeType"/>
        </template>
</el-table-column> -->
      <!-- <el-table-column label="实时库存" align="center" prop="currentStock" /> -->
      <!-- <el-table-column label="业务参考号" align="center" prop="businessRef" /> -->
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status"/>
        </template>
      </el-table-column> -->
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:stockLogs:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:stockLogs:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改库存变动日志对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="stockLogsRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="商品编号" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入商品编号" />
        </el-form-item> -->
        <el-form-item label="商品编号" prop="goodsId">
          <el-select filterable v-model="form.goodsId" placeholder="请选择商品" style="width: 100%">
            <el-option v-for="item in goodsList" :key="item.goodsId" :label="item.goodsName" :value="item.goodsId" />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <!-- <el-form-item label="商品规格ID" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入商品规格ID" />
        </el-form-item> -->
        <!-- <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="工单ID" prop="workId">
          <el-input v-model="form.workId" placeholder="请输入工单ID" />
        </el-form-item> -->
        <el-form-item label="变动数量" prop="changeQuantity">
          <el-input v-model="form.changeQuantity" placeholder="请输入变动数量" />
        </el-form-item>
        <!-- <el-form-item label="变动类型" prop="changeType">
          <el-select v-model="form.changeType" placeholder="请选择变动类型">
            <el-option
              v-for="dict in change_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="实时库存" prop="currentStock">
          <el-input v-model="form.currentStock" placeholder="请输入实时库存" />
        </el-form-item> -->
        <!-- <el-form-item label="业务参考号" prop="businessRef">
          <el-input v-model="form.businessRef" placeholder="请输入业务参考号" />
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in wdm_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio v-for="dict in del_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商品详情信息组件 -->
    <GoodsInfoDetail v-model="goodsDetailVisible" :goods-id="currentGoodsId" :wdm_status="wdm_status" />
  </div>
</template>

<script setup name="StockLogs">
import GoodsInfoDetail from "@/views/components/goodsInfoDetail.vue";
import {
  listStockLogs,
  getStockLogs,
  delStockLogs,
  addStockLogs,
  updateStockLogs,
} from "@/api/ruoyi/stockLogs";

import { listGoods, excludeExistsGoods } from "@/api/ruoyi/goods";

const { proxy } = getCurrentInstance();
const { wdm_status, change_type, del_flag } = proxy.useDict(
  "wdm_status",
  "change_type",
  "del_flag"
);

const stockLogsList = ref([]);
const goodsList = ref([]);

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    skuId: null,
    orderId: null,
    workId: null,
    changeType: null,
    businessRef: null,
    status: null,
    version: null,
    goodsId: null,
    title: null,
  },
  rules: {
    goodsId: [{ required: true, message: "商品编号不能为空", trigger: "blur" }],
    changeQuantity: [
      { required: true, message: "变动数量不能为空", trigger: "blur" },
      // { type: 'number', message: '变动数量必须为数字' }
    ],
    // skuId: [
    //   { required: true, message: "商品规格ID不能为空", trigger: "blur" }
    // ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询库存变动日志列表 */
function getList() {
  loading.value = true;
  listStockLogs(queryParams.value).then((response) => {
    // stockLogsList.value = response.rows;
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    stockLogsList.value = response.rows.filter(
      (item) => item.delFlag !== "2"
    );
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询商品信息列表 */
const goodsLoaded = ref(false);

function getgoodsList() {
  if (goodsLoaded.value) return;
  excludeExistsGoods()
    .then((response) => {
      goodsList.value = response.rows.filter(
        (item) => item.goodsId && item.goodsName
      );
      goodsLoaded.value = true;
    })
    .catch((error) => {
      proxy.$modal.msgError("获取商品列表失败，请稍后重试");
      console.error("获取商品列表失败:", error);
    });
}

// 添加响应式变量
const goodsDetailVisible = ref(false);
const currentGoodsId = ref(null);

// 打开商品详情信息组件

function handleGoodsInfo(row) {
  if (!row.goodsId) {
    proxy.$modal.msgWarning("该记录没有关联商品信息");
    return;
  }

  currentGoodsId.value = row.goodsId;
  goodsDetailVisible.value = true;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    logId: null,
    skuId: null,
    orderId: null,
    workId: null,
    changeQuantity: null,
    changeType: null,
    currentStock: null,
    businessRef: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    goodsId: null,
    title: null,
  };
  proxy.resetForm("stockLogsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.logId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加库存变动日志";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _logId = row.logId || ids.value;
  getStockLogs(_logId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改库存变动日志";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stockLogsRef"].validate((valid) => {
    if (valid) {
      if (form.value.logId != null) {
        updateStockLogs(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStockLogs(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _logIds = row.logId || ids.value;
  proxy.$modal
    .confirm('是否确认删除库存变动日志编号为"' + _logIds + '"的数据项？')
    .then(function () {
      return delStockLogs(_logIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/stockLogs/export",
    {
      ...queryParams.value,
    },
    `stockLogs_${new Date().getTime()}.xlsx`
  );
}

getList();

getgoodsList();
</script>
